/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.teach.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

import com.lczyfz.istep.modules.resource.entity.*;
import com.lczyfz.istep.modules.resource.service.*;
import com.lczyfz.istep.modules.sys.service.SystemService;
import com.lczyfz.istep.modules.sys.utils.UserUtils;
import com.lczyfz.istep.modules.teach.entity.TeachExam;
import com.lczyfz.istep.modules.teach.entity.TeachStudentExam;
import com.lczyfz.istep.modules.teach.service.TeachExamService;
import com.lczyfz.istep.modules.teach.service.TeachStudentExamService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.modules.teach.entity.TeachStudentPaper;
import com.lczyfz.istep.modules.teach.service.TeachStudentPaperService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 学生考试中间表Controller
 * @author cqh
 * @version 2017-05-16
 */
@Controller
@RequestMapping(value = "${adminPath}/teach/teachStudentPaper")
public class TeachStudentPaperController extends BaseController {

	@Autowired
	private TeachExamService teachExamService;

	@Autowired
	private ResourceQuestionAnswerService resourceQuestionAnswerService;

	@Autowired
	private ResourceQuestionOptionService resourceQuestionOptionService;

	@Autowired
	private ResourcePaperService resourcePaperService;

	@Autowired
	private ResourceQuestionService resourceQuestionService;

	@Autowired
	private ResourcePaperQuestionService resourcePaperQuestionService;

	@Autowired
	private SystemService systemService;

	@Autowired
	private TeachStudentPaperService teachStudentPaperService;

	@Autowired
	private TeachStudentExamService teachStudentExamService;


	@ModelAttribute
	public TeachExam get(@RequestParam(required=false) String id) {
		TeachExam entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = teachExamService.get(id);
		}
		if (entity == null){
			entity = new TeachExam();
		}
		return entity;
	}

//	@ModelAttribute
//	public TeachStudentPaper getTeachStudentPaper(String id) {
//		TeachStudentPaper entity = null;
//		if (StringUtils.isNotBlank(id)){
//			entity = teachStudentPaperService.get(id);
//		}
//		if (entity == null){
//			entity = new TeachStudentPaper();
//		}
//		return entity;
//	}



//	@RequiresPermissions("teach:teachStudentPaper:view")
//	@RequestMapping(value = {"list", ""})
//	public String list(TeachStudentPaper teachStudentPaper, HttpServletRequest request, HttpServletResponse response, Model model) {
//		Page<TeachStudentPaper> page = teachStudentPaperService.findPage(new Page<TeachStudentPaper>(request, response), teachStudentPaper);
//		model.addAttribute("page", page);
//		return "modules/teach/teachStudentPaperList";
//	}
//
//	@RequiresPermissions("teach:teachStudentPaper:view")
//	@RequestMapping(value = "form")
//	public String form(TeachStudentPaper teachStudentPaper, Model model) {
//		model.addAttribute("teachStudentPaper", teachStudentPaper);
//		return "modules/teach/teachStudentPaperForm";
//	}
//
//	@RequiresPermissions("teach:teachStudentPaper:edit")
//	@RequestMapping(value = "save")
//	public String save(TeachStudentPaper teachStudentPaper, Model model, RedirectAttributes redirectAttributes) {
//		if (!beanValidator(model, teachStudentPaper)){
//			return form(teachStudentPaper, model);
//		}
//		teachStudentPaperService.save(teachStudentPaper);
//		addMessage(redirectAttributes, "保存学生考试中间表成功");
//		return "redirect:"+Global.getAdminPath()+"/teach/teachStudentPaper/?repage";
//	}
//
//	@RequiresPermissions("teach:teachStudentPaper:edit")
//	@RequestMapping(value = "delete")
//	public String delete(TeachStudentPaper teachStudentPaper, RedirectAttributes redirectAttributes) {
//		teachStudentPaperService.delete(teachStudentPaper);
//		addMessage(redirectAttributes, "删除学生考试中间表成功");
//		return "redirect:"+Global.getAdminPath()+"/teach/teachStudentPaper/?repage";
//	}


	//我的考试-列表展示
	@RequiresPermissions("teach:teachStudentPaper:view")
	@RequestMapping(value = {"stuExamList", ""})
	public String stuExamList(TeachExam teachExam, HttpServletRequest request, HttpServletResponse response, Model model) {
//		Page<TeachExam> page = teachExamService.findPage(new Page<TeachExam>(request, response), teachExam);
		//AllisaYe

		String paperId = request.getParameter("paperId") ;
		if(paperId != null && !paperId.equals("")){
			teachExam.setId(paperId);
		}

//		String userId= UserUtils.getUser().getId();
//		Page<TeachExam> page = teachExamService.findExamListPageById(new Page<TeachExam>(request, response), teachExam,userId);

		teachExam.setUserId(UserUtils.getUser().getId());
		Page<TeachExam> page = teachExamService.findExamListPageById(new Page<TeachExam>(request, response), teachExam);


//		logger.debug("====AlisaYe===page.getList().get(0).getId();=== [{}]",page.getList().get(0).getId());
		model.addAttribute("page", page);
//		List<TeachExam> teachExam0=teachExamService.findExamListById(id);
//		logger.debug("====AlisaYe===teachExam000=== [{}]",teachExam0);
//		model.addAttribute(teachExam0);

		return "modules/teach/stuExamList";
	}


	/**
	 * 试卷预览，
	 * 通过考试examId得到试卷的Id
	 * 在通过试卷id得到试卷的部分
	 */

	public ResourcePaper getResourcePaper(String id) {
		ResourcePaper entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = resourcePaperService.get(id);
		}
		if (entity == null){
			entity = new ResourcePaper();
		}
		return entity;
	}


	@RequiresPermissions("teach:teachStudentPaper:view")
	@RequestMapping(value = "stuExamAnswerDetail")
	public String stuExamAnswerDetail(TeachExam teachExam, Model model,String examId) {

		//根据试卷id生成试卷预览
//		logger.debug("====AlisaYe===examId=== [{}]",examId);
		List<ResourcePaper> resourcePaper00=teachExamService.findPaperByExamId(examId);
		ResourcePaper resourcePaper0=resourcePaper00.get(0);

		String id=UserUtils.getUser().getId();
		String paperId=resourcePaper0.getId();
		ResourcePaper resourcePaper=getResourcePaper(paperId);
//		logger.debug("====AlisaYe===id=== [{}]",id);
//		logger.debug("====AlisaYe===paperId=== [{}]",paperId);
		List<TeachStudentPaper> teachStudentPaper=teachStudentPaperService.findStuAnswerList(id,paperId);
//		logger.debug("====AlisaYe===teachStudentPaper=== [{}]",teachStudentPaper);

		String userId=UserUtils.getUser().getId();
		List<TeachStudentPaper> getAllScore=teachStudentPaperService.getAllScoreByUserIdAndPaperId(userId,paperId);
		int stuTotalScore=0;
		for(int i=0;i<getAllScore.size();i++){
			String s =getAllScore.get(i).getScore();
//			logger.debug("====AlisaYe=getAllScore==ssssssssssssssssssssssssss=== [{}]",s);
			stuTotalScore =stuTotalScore+ Integer.parseInt(s);
		}
//		logger.debug("====AlisaYe=getAllScore==sssssstuTotalScoressssssssss=== [{}]",stuTotalScore);
		String stuTotalScoreS=stuTotalScore+"";

		//================================
//		logger.debug("====AlisaYe===paperId=== [{}]",paperId);
////		获得试卷的所有题目
//		List<ResourceQuestion> resourceQuestionList=teachExamService.findQuesType0ByPaperId(paperId);
//		logger.debug("====AlisaYe===resourceQuestion.size()== [{}]", resourceQuestionList.size());
//		for(int i=0;i<resourceQuestionList.size();i++)
//		{
//		}
		//==============================================

		//----------------------------------

		List<TeachExam> ifCheckAnswerList=teachStudentPaperService.getIfCheckAnswerByExamId(examId);
		String ifCheckAnswer="0";//默认为0是看不见答案
//		logger.debug("====AlisaYe===ifCheckAnswerList.size()examId== [{}]", examId);
//		logger.debug("====AlisaYe===ifCheckAnswerList.size()== [{}]", ifCheckAnswerList.size());
		if(ifCheckAnswerList.size()>0){
			ifCheckAnswer=ifCheckAnswerList.get(0).getIfCheckAnswer();
//			logger.debug("====AlisaYe=size==ifCheckAnswer== [{}]", ifCheckAnswer);
		}
//		logger.debug("====AlisaYe===ifCheckAnswer== [{}]", ifCheckAnswer);

		List<ResourceQuestionAnswer>  resourceQuestionAnswer=teachStudentPaperService.getQuestionAnswerList(paperId);

//		if(resourceQuestionAnswer.size()>0)
//		logger.debug("====AlisaYe===resourceQuestionAnswer== [{}]", resourceQuestionAnswer);





		List<ResourceQuestion> resourceQuestionList = new ArrayList<ResourceQuestion>();
		ResourcePaper paper = resourcePaperService.get(paperId);
		ResourcePaperQuestion resourcePaperQuestion = new ResourcePaperQuestion();
		resourcePaperQuestion.setPaperId(paperId);

		List<ResourcePaperQuestion> paperQuestions = resourcePaperQuestionService.findList(resourcePaperQuestion);
		for(ResourcePaperQuestion paperQuestion : paperQuestions){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			resourceQuestionList.add(question);
		}
		for(ResourceQuestion question:resourceQuestionList)
		{
			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//		AlisaYe20170703---新的页面修改部分控制器（题型分成四类分别处理）
		List<ResourceQuestion> resourceQuestionListRadio = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListCheckbox = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListJudement = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListShortAnswer = new ArrayList<ResourceQuestion>();

		ResourcePaperQuestion resourcePaperQuestionWW = new ResourcePaperQuestion();
//		resourcePaperQuestion.setPaperId(id);//原
//		resourcePaperQuestionWW.setPaperId(id);//改
//		resourcePaperQuestion.setPaperId(paperId);
		resourcePaperQuestionWW.setPaperId(paperId);

//		logger.debug("resourcePaperQuestion.setPaperId(id)",resourcePaperQuestionWW.getPaperId());
		List<ResourcePaperQuestion> paperQuestionsWW = resourcePaperQuestionService.findList(resourcePaperQuestionWW);
//		logger.debug("lsjj===paperQuestionsWW=***123********== [{}]",paperQuestionsWW.size());
		//单选题
		for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==0) {
				resourceQuestionListRadio.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListRadio)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

		//多选题
		for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==1) {
				resourceQuestionListCheckbox.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListCheckbox)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//			判断题
		for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==2) {
				resourceQuestionListJudement.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListJudement)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//		简答题
		for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==3) {
				resourceQuestionListShortAnswer.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListShortAnswer)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//
//		ResourcePaperQuestion resourcePaperQuestion = new ResourcePaperQuestion();
//		List<ResourcePaperQuestion> resourcePaperQuestionsList = resourcePaperQuestionService.findList(resourcePaperQuestion);
//		for(ResourcePaperQuestion question:resourcePaperQuestionsList)
//		{
//			ResourceQuestionOption option = new ResourceQuestionOption();
//			option.setQuestionId(question.getId());
//			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
//
//		}

		model.addAttribute("resourceQuestionListRadio",resourceQuestionListRadio);
//		logger.debug("====AlisaYe===resourceQuestionListRadio.size()examId== [{}]", resourceQuestionListRadio);
		model.addAttribute("resourceQuestionListCheckbox",resourceQuestionListCheckbox);
		model.addAttribute("resourceQuestionListJudement",resourceQuestionListJudement);
		model.addAttribute("resourceQuestionListShortAnswer",resourceQuestionListShortAnswer);
//		AlisaYe20170703---新的页面修改部分控制器（题型分成四类分别处理）





		model.addAttribute("resourceQuestionList",resourceQuestionList);

		model.addAttribute("resourcePaper", resourcePaper);

		model.addAttribute("teachStudentPaper", teachStudentPaper);
		model.addAttribute("paperId", paperId);

		model.addAttribute("stuTotalScoreS", stuTotalScoreS);

		model.addAttribute("ifCheckAnswer",ifCheckAnswer);
		model.addAttribute("resourceQuestionAnswer",resourceQuestionAnswer);

		//---------------------------------


		//=============================================================
//		ResourceQuestion resourceQuestion=new ResourceQuestion();
//		model.addAttribute("resourceQuestion",resourceQuestion);
//		model.addAttribute("resourceQuestionList",resourceQuestionList);
////		model.addAttribute("teachExam", teachExam);
////		model.addAttribute("resourcePaperQuestion",resourcePaperQuestion);
//		model.addAttribute("resourcePaper", resourcePaper0);
		//=============================================================

		return "modules/teach/stuExamAnswerDetail";
	}




	@ModelAttribute
	public TeachStudentPaper getTeachStudentPaper(String id) {
		TeachStudentPaper entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = teachStudentPaperService.get(id);
		}
		if (entity == null){
			entity = new TeachStudentPaper();
		}
		return entity;
	}

	//进入考试页面
	@RequiresPermissions("teach:teachStudentPaper:view")
	@RequestMapping(value = "stuExamDoTest")
	public String stuExamDoTest(TeachExam teachExam, Model model,String examId) {

		String userId= UserUtils.getUser().getId();

		List<TeachExam> teachExamTime=teachExamService.findTeachExamByExamId(examId);
		Date totalEndDate=new Date();
		totalEndDate.setTime(totalEndDate.getTime()+120*60*1000);

		Date endDate=new Date();//totalEndDate
		if(teachExamTime.size()>0){
			totalEndDate=teachExamTime.get(0).getEndDate();//获取该门考试最后截止时间
			String answerTime0=teachExamTime.get(0).getAnswerTime();
			int answerTime=Integer.parseInt(answerTime0);
			endDate.setTime(new Date().getTime()+answerTime*60*1000);
		}


		//查询数据库是否有该生的考试的截止时间
		List<TeachStudentExam> firstTime0=teachStudentExamService.findFirstTimeAndCountByExamId(examId,userId);
		if(firstTime0.size()>0)
		{
//			logger.debug("==***********==endDate===firstTime0.get(0)=***********== [{}] ",firstTime0.get(0));
			//如果该生的考试时间是空的
			if(firstTime0.get(0).getFirstTime()==null){

				//设置该生的考试截止时间
				List<TeachExam> answerTimeList=teachStudentExamService.findAnswerTimeByExamId(examId);
				if(answerTimeList.size()>0){
					String answerTime0=answerTimeList.get(0).getAnswerTime();
					int answerTime=Integer.parseInt(answerTime0);
					endDate=new Date();
					endDate.setTime(endDate.getTime() + answerTime*60*1000);

					//如果考试的截止时间在最终截止考试时间之后，考试的截止时间应该是最后的总的截止时间，即考生的考试时间变短了
					if(endDate.compareTo(totalEndDate)>0){
						endDate.setTime(totalEndDate.getTime());

					}
					teachStudentExamService.setFirstTimeByExamId(examId,userId,endDate);
				}

				firstTime0.get(0).setFirstTime(endDate);
			}else{
				//考试时间不为空，则读入考试的截止时间
				endDate=firstTime0.get(0).getFirstTime();
			}
		}

		//获取点击答题的时间
		Date firstStartDoExamTime=new Date();//获取当前的时间startDoExamTime，就是第一次考试考试的时间，需要对这个值做判断
		//获取总的答题时间，

		List<ResourcePaper> resourcePaper00=teachExamService.findPaperByExamId(examId);
		ResourcePaper resourcePaper0=resourcePaper00.get(0);

		String id=UserUtils.getUser().getId();
		String paperId=resourcePaper0.getId();
		ResourcePaper resourcePaper=getResourcePaper(paperId);
//		logger.debug("==20170928==AlisaYe===resourcePaper=== [{}]",resourcePaper);
//		logger.debug("====AlisaYe===id=== [{}]",id);
//		logger.debug("====AlisaYe===paperId=== [{}]",paperId);
		List<TeachStudentPaper> teachStudentPaper=teachStudentPaperService.findStuAnswerList(id,paperId);
//		logger.debug("====AlisaYe===teachStudentPaper=== [{}]",teachStudentPaper);

		List<TeachStudentPaper> teachStudentPaperDo=teachStudentPaperService.findStuAnswerList(id,paperId);
//		logger.debug("===20170928==AlisaYe===teachStudentPaper=== [{}]",teachStudentPaperDo);



		List<ResourceQuestion> resourceQuestionList = new ArrayList<ResourceQuestion>();
		ResourcePaper paper = resourcePaperService.get(paperId);
		ResourcePaperQuestion resourcePaperQuestion = new ResourcePaperQuestion();
		resourcePaperQuestion.setPaperId(paperId);

		List<ResourcePaperQuestion> paperQuestions = resourcePaperQuestionService.findList(resourcePaperQuestion);
		for(ResourcePaperQuestion paperQuestion : paperQuestions){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			resourceQuestionList.add(question);
		}
		for(ResourceQuestion question:resourceQuestionList)
		{
			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}





		model.addAttribute("resourceQuestionList",resourceQuestionList);
		model.addAttribute("resourcePaper", resourcePaper);
		model.addAttribute("paperId", paperId);

//		model.addAttribute("resourceQuestionAA", resourceQuestionList);
		model.addAttribute("teachStudentPaper", teachStudentPaperDo);
		model.addAttribute("examId", examId);





//		AlisaYe20170703---新的页面修改部分控制器（题型分成四类分别处理）
		List<ResourceQuestion> resourceQuestionListRadio = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListCheckbox = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListJudement = new ArrayList<ResourceQuestion>();
		List<ResourceQuestion> resourceQuestionListShortAnswer = new ArrayList<ResourceQuestion>();

		ResourcePaperQuestion resourcePaperQuestionWW = new ResourcePaperQuestion();
		resourcePaperQuestionWW.setPaperId(paperId);


		List<ResourcePaperQuestion> paperQuestionsWW = resourcePaperQuestionService.findList(resourcePaperQuestionWW);

		//单选题
		for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==0) {
				resourceQuestionListRadio.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListRadio)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

		//多选题
		for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==1) {
				resourceQuestionListCheckbox.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListCheckbox)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//			判断题
		for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==2) {
				resourceQuestionListJudement.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListJudement)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

//		简答题
		for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
			ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
			question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
			if(Integer.valueOf(question.getQuestionType())==3) {
				resourceQuestionListShortAnswer.add(question);
			}

		}
		for(ResourceQuestion question:resourceQuestionListShortAnswer)
		{

			ResourceQuestionOption option = new ResourceQuestionOption();
			option.setQuestionId(question.getId());

			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
		}

		model.addAttribute("resourceQuestionListRadio",resourceQuestionListRadio);
//		logger.debug("====AlisaYe===resourceQuestionListRadio.size()examId== [{}]", resourceQuestionListRadio);
		model.addAttribute("resourceQuestionListCheckbox",resourceQuestionListCheckbox);
		model.addAttribute("resourceQuestionListJudement",resourceQuestionListJudement);
		model.addAttribute("resourceQuestionListShortAnswer",resourceQuestionListShortAnswer);
//		AlisaYe20170703---新的页面修改部分控制器（题型分成四类分别处理）

//倒计时获取考试结束时间
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(endDate); //设置时间为当前时间
		int year = ca.get(Calendar.YEAR);//获取年份
		int month=ca.get(Calendar.MONTH)+1;//获取月份
		int day=ca.get(Calendar.DATE);//获取日
		int hour=ca.get(Calendar.HOUR_OF_DAY);//小时
		int minute=ca.get(Calendar.MINUTE);//分
		int second=ca.get(Calendar.SECOND);//秒    2017/05/16 20:27:30
		//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
		String teachExamEndDate=year+"/"+month+"/"+day+" "+hour+":"+minute+":"+second;

		model.addAttribute("teachExamEndDate",teachExamEndDate);
//		logger.debug("AlisaYe===结束时间=" + teachExamEndDate);
//		List<SceneEnvironmentInstanceOs> vmList=sceneEnvironmentInstanceService.findVmTemplateListByInstanceId(sceneEnvironmentInstance);
		String stuDoCount="520";
		if(teachStudentExamService.findFirstTimeAndCountByExamId(examId,userId).size()>0){
			stuDoCount=teachStudentExamService.findFirstTimeAndCountByExamId(examId,userId).get(0).getExamFrequency();
			if(teachStudentExamService.findFirstTimeAndCountByExamId(examId,userId).get(0).getExamFrequency().equals("0")){
				stuDoCount=teachStudentExamService.findFirstTimeAndCountByExamId(examId,userId).get(0).getExamFrequency();
			}
		}

		//向考试界面提交
		model.addAttribute("stuDoCount", stuDoCount);

		return "modules/teach/stuExamDoTest";
	}


	@RequiresPermissions("teach:teachStudentPaper:view")
	@RequestMapping(value = "answerSave")
	public String stuExamDoTestAnswerSave(TeachExam teachExam, HttpServletRequest request, HttpServletResponse response,Model model,String paperId,String answerTotalToString,int questionCount,String examId,String labelBnt){
		String userId=UserUtils.getUser().getId();
		//labelBnt保存baocun
		//labelBnt提交tijiao
//		logger.debug("====AlisaYe===examId898989=== [{}]",examId);
//		logger.debug("====AlisaYe===labelBntlabelBntlabelBntlabelBnt=== [{}]",labelBnt);
		//AlisaYe测试测试传值
//		if(paperId!=null){
//			logger.debug("====AlisaYe===paperId=== [{}]",paperId);
//		}
//		if(answerTotalToString!=null){
//			logger.debug("====AlisaYe===answerTotalToString=== [{}]",answerTotalToString);
//		}
//		logger.debug("====labelBntlabelBnt===row=== [{}]",labelBnt);

//		从answerTotalToString获取所有题目的答案，进行切分并获得对应题目id和学生答案，存入数据库（前段页面记录显示之前保存的答案）
		teachStudentPaperService.deleteStudentAnswerByuserIdandPaperId(userId,paperId);
		String row=answerTotalToString;
//		logger.debug("====AlisaYe===row=== [{}]",row);
		String row1[]=new String[questionCount+1];
		String row2[]=new String[questionCount+1];
//		logger.debug("====AlisaYe===questionCount=== [{}]",questionCount);
		//1(!(Question|#|StudentAnswer)!)#(#endQuestion#)#3(!(Question|#|StudentAnswer)!)#(#endQuestion#)#
		//根据拼接的规则把每个题和对应答案切分出来
		row1=row.split("#\\(#endQuestion#\\)#");
		for(int i=0;i<row1.length;i++)
		{
			//切分每一个题目为题目id和学生答案两个部分
			row2=row1[i].split("\\(!\\(Question\\|#\\|StudentAnswer\\)!\\)");
//
//			logger.debug("====AlisaYe===row2.length===[{}]",row2.length);//如果row2.length==1，说明没有选择答案。
//
//				if(row2.length==2){
//					logger.debug("====AlisaYe===row2[i]===[{}]",row2[0]);//quewtionID
//					logger.debug("====AlisaYe===row2[i]===[{}]",row2[1]);//studentAnswer
//				}
//				if(row2.length==1){
//					logger.debug("====AlisaYe===row2[i]===[{}]",row2[0]);//quewtionID
//					logger.debug("====AlisaYe===studentAnswer======没有答案！");//studentAnswer
//				}
//			questionCount是题目总数量，有多少题目就插入到表teach_studeng_paper多少次数据
//			数据userId-》String userId=UserUtils.getUser().getId();
//			paperId从前一个控制器传过来了
//			每条数据中如果切割的row2.length==1,说明没有作答，默认给答案赋值为“-1”，若row2.length==2，则赋值row2[1]。
//			分值score是判断标准答案表格的答案和学生答案是否相同给出成绩，这个模块暂时不做，待商榷

			//First在数据库中把userId和paperId相同的所有试卷的答案删除。

			//Second向数据库插入一组数据
			TeachStudentPaper studentAnswer=new TeachStudentPaper();
			studentAnswer.setUserId(userId);
			studentAnswer.setPaperId(paperId);
			studentAnswer.setQuestionId(row2[0]);
			int sscore;
			String aanswer;

			//获得这道题的分值ss和答案aa
			if(teachStudentPaperService.getScoreByPaperIdAndQuestionId(paperId, row2[0]).size()>0){
				sscore=teachStudentPaperService.getScoreByPaperIdAndQuestionId(paperId, row2[0]).get(0).getScore();
			}else{
				sscore=0;
			}

			if(teachStudentPaperService.getRightAnswerByQuestionId(row2[0]).size()>0){
				aanswer=teachStudentPaperService.getRightAnswerByQuestionId(row2[0]).get(0).getAnswer();
			}else{
				aanswer="null";
			}


			if(row2.length==2){
				studentAnswer.setAnswer(row2[1]);
				//在这里做答题结果的判断，单选多选。简答题的判题也是很难的说？aa是正确答案;
				if(aanswer.equals(row2[1])){
					studentAnswer.setScore(sscore+"");
				}else{
					studentAnswer.setScore("0");
				}
			}
			if(row2.length==1){
				studentAnswer.setAnswer("-1");
				studentAnswer.setScore("0");
			}

			teachStudentPaperService.save(studentAnswer);
		}
		//保存答题情况后跳转列表页面


		if(labelBnt.endsWith("tijiao")){
			String examFrequency;
			List<TeachStudentExam> examFrequency00=teachStudentExamService.findFirstTimeAndCountByExamId(examId,userId);
			if(examFrequency00.size()>0)
			{
				examFrequency=examFrequency00.get(0).getExamFrequency();
//				logger.debug("====AlisaYe===examFrequency321===[{}]",examFrequency);
			}else{
				List<TeachExam> teachExamTime=teachExamService.findTeachExamByExamId(examId);
				examFrequency=teachExamTime.get(0).getExamFrequency();

				//examFrequency="100";
			}
			int examFrequencyInt = Integer.parseInt(examFrequency);
			examFrequencyInt=examFrequencyInt-1;
			examFrequency=examFrequencyInt+"";
			teachStudentExamService.setexamFrequencyByExamId(examId,userId, examFrequency);
//			logger.debug("====AlisaYe===examFrequency3210===[{}]",examFrequency);

//			Page<TeachExam> page = teachExamService.findExamListPageById(new Page<TeachExam>(request, response), teachExam,userId);
			teachExam.setUserId(UserUtils.getUser().getId());
			Page<TeachExam> page = teachExamService.findExamListPageById(new Page<TeachExam>(request, response), teachExam);
			model.addAttribute("page", page);
			return "modules/teach/stuExamList";
		}else if(labelBnt.endsWith("baocun")){
			//**********************stuExamDoTest的控制器方法***********************

//			TeachExam teachExamTime=teachExamService.findTeachExamByExamId(examId);
//			Date totalEndDate=teachExamTime.getEndDate();//获取该门考试最后截止时间
//			Date endDate=new Date();//totalEndDate
//			logger.debug("==***********==examId123=***********== [{}] ",examId);
			List<TeachExam> teachExamTime=teachExamService.findTeachExamByExamId(examId);
			Date totalEndDate=new Date();
			totalEndDate.setTime(totalEndDate.getTime()+120*60*1000);
			if(teachExamTime.size()>0){
				totalEndDate=teachExamTime.get(0).getEndDate();//获取该门考试最后截止时间
			}
			Date endDate=new Date();//totalEndDate

			//查询数据库是否有该生的考试的截止时间
//			logger.debug("==***********==examId123123=***********== [{}] ",examId);
			List<TeachStudentExam> firstTime0=teachStudentExamService.findFirstTimeAndCountByExamId(examId,userId);
			if(firstTime0.size()>0)
			{
				//如果该生的考试时间是空的
				if(firstTime0.get(0).getFirstTime()==null){

					//设置该生的考试截止时间
					List<TeachExam> answerTimeList=teachStudentExamService.findAnswerTimeByExamId(examId);
					if(answerTimeList.size()>0){
						String answerTime0=answerTimeList.get(0).getAnswerTime();
						int answerTime=Integer.parseInt(answerTime0);
						endDate=new Date();
						endDate.setTime(endDate.getTime() + answerTime*60*1000);

						//如果考试的截止时间在最终截止考试时间之后，考试的截止时间应该是最后的总的截止时间，即考生的考试时间变短了
						if(endDate.compareTo(totalEndDate)>0){
							endDate.setTime(totalEndDate.getTime());

						}
//						logger.debug("==***********==examId123123123=***********== [{}] ",examId);
						teachStudentExamService.setFirstTimeByExamId(examId,userId,endDate);
					}

					firstTime0.get(0).setFirstTime(endDate);
				}else{
					//考试时间不为空，则读入考试的截止时间
					endDate=firstTime0.get(0).getFirstTime();
				}
			}

			List<ResourcePaper> resourcePaper00=teachExamService.findPaperByExamId(examId);
			ResourcePaper resourcePaper0=resourcePaper00.get(0);
			String id=UserUtils.getUser().getId();
			paperId=resourcePaper0.getId();
			ResourcePaper resourcePaper=getResourcePaper(paperId);
			List<TeachStudentPaper> teachStudentPaper=teachStudentPaperService.findStuAnswerList(id,paperId);
			List<TeachStudentPaper> teachStudentPaperDo=teachStudentPaperService.findStuAnswerList(id,paperId);
//			logger.debug("==***********=teacid,paperIdntPaperDo=*****[{}]******== [{}] ",id,paperId);
//			logger.debug("==***********=teachStudentPaperDoteachStudentPaperDo=***********== [{}] ",teachStudentPaperDo);
//			logger.debug("==***********=teachStudentPaper=****teachStudentPaper*******== [{}] ",teachStudentPaper);
			List<ResourceQuestion> resourceQuestionList = new ArrayList<ResourceQuestion>();
			ResourcePaper paper = resourcePaperService.get(paperId);
			ResourcePaperQuestion resourcePaperQuestion = new ResourcePaperQuestion();
			resourcePaperQuestion.setPaperId(paperId);
			List<ResourcePaperQuestion> paperQuestions = resourcePaperQuestionService.findList(resourcePaperQuestion);
			for(ResourcePaperQuestion paperQuestion : paperQuestions){
				ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
				resourceQuestionList.add(question);
			}
			for(ResourceQuestion question:resourceQuestionList)
			{
				ResourceQuestionOption option = new ResourceQuestionOption();
				option.setQuestionId(question.getId());

				question.setOption(resourceQuestionOptionService.getByQuestionId(option));
			}
			model.addAttribute("resourceQuestionList",resourceQuestionList);
			model.addAttribute("resourcePaper", resourcePaper);
//			logger.debug("==***********=paperIdpaperIdpaperIdpaperIdpaperId=***********== [{}] ",paperId);
//			logger.debug("==***********=examIdexamIdexamIdexamIdexamIdexamId=***********== [{}] ",examId);
//			logger.debug("==***********=teachStudentPaperteachStudentPaperteachStudentPaper=***********== [{}] ",teachStudentPaper);
			model.addAttribute("paperId", paperId);
			model.addAttribute("teachStudentPaper", teachStudentPaperDo);
			model.addAttribute("examId", examId);


//		AlisaYe20170703---新的页面修改部分控制器（题型分成四类分别处理）
			List<ResourceQuestion> resourceQuestionListRadio = new ArrayList<ResourceQuestion>();
			List<ResourceQuestion> resourceQuestionListCheckbox = new ArrayList<ResourceQuestion>();
			List<ResourceQuestion> resourceQuestionListJudement = new ArrayList<ResourceQuestion>();
			List<ResourceQuestion> resourceQuestionListShortAnswer = new ArrayList<ResourceQuestion>();

			ResourcePaperQuestion resourcePaperQuestionWW = new ResourcePaperQuestion();
//			resourcePaperQuestion.setPaperId(id);//原
//			resourcePaperQuestionWW.setPaperId(id);//改
//			resourcePaperQuestion.setPaperId(paperId);
			resourcePaperQuestionWW.setPaperId(paperId);

//			logger.debug("resourcePaperQuestion.setPaperId(id)",resourcePaperQuestionWW.getPaperId());

			List<ResourcePaperQuestion> paperQuestionsWW = resourcePaperQuestionService.findList(resourcePaperQuestionWW);
//			logger.debug("lsjj===paperQuestionsWW=",paperQuestionsWW);
			//单选题
			for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
				ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
				question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
				if(Integer.valueOf(question.getQuestionType())==0) {
					resourceQuestionListRadio.add(question);
				}

			}
			for(ResourceQuestion question:resourceQuestionListRadio)
			{

				ResourceQuestionOption option = new ResourceQuestionOption();
				option.setQuestionId(question.getId());

				question.setOption(resourceQuestionOptionService.getByQuestionId(option));
			}

			//多选题
			for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
				ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
				question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
				if(Integer.valueOf(question.getQuestionType())==1) {
					resourceQuestionListCheckbox.add(question);
				}

			}
			for(ResourceQuestion question:resourceQuestionListCheckbox)
			{

				ResourceQuestionOption option = new ResourceQuestionOption();
				option.setQuestionId(question.getId());

				question.setOption(resourceQuestionOptionService.getByQuestionId(option));
			}

//			判断题
			for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
				ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
				question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
				if(Integer.valueOf(question.getQuestionType())==2) {
					resourceQuestionListJudement.add(question);
				}

			}
			for(ResourceQuestion question:resourceQuestionListJudement)
			{

				ResourceQuestionOption option = new ResourceQuestionOption();
				option.setQuestionId(question.getId());

				question.setOption(resourceQuestionOptionService.getByQuestionId(option));
			}

//		简答题
			for(ResourcePaperQuestion paperQuestion : paperQuestionsWW){
				ResourceQuestion question = resourceQuestionService.get(paperQuestion.getQuestionId());
				question.setQuestionScore(String.valueOf(paperQuestion.getScore()));
				if(Integer.valueOf(question.getQuestionType())==3) {
					resourceQuestionListShortAnswer.add(question);
				}

			}
			for(ResourceQuestion question:resourceQuestionListShortAnswer)
			{

				ResourceQuestionOption option = new ResourceQuestionOption();
				option.setQuestionId(question.getId());

				question.setOption(resourceQuestionOptionService.getByQuestionId(option));
			}

//
//		ResourcePaperQuestion resourcePaperQuestion = new ResourcePaperQuestion();
//		List<ResourcePaperQuestion> resourcePaperQuestionsList = resourcePaperQuestionService.findList(resourcePaperQuestion);
//		for(ResourcePaperQuestion question:resourcePaperQuestionsList)
//		{
//			ResourceQuestionOption option = new ResourceQuestionOption();
//			option.setQuestionId(question.getId());
//			question.setOption(resourceQuestionOptionService.getByQuestionId(option));
//
//		}

			model.addAttribute("resourceQuestionListRadio",resourceQuestionListRadio);
//			logger.debug("====AlisaYe===resourceQuestionListRadio.size()examId== [{}]", resourceQuestionListRadio);
			model.addAttribute("resourceQuestionListCheckbox",resourceQuestionListCheckbox);
			model.addAttribute("resourceQuestionListJudement",resourceQuestionListJudement);
			model.addAttribute("resourceQuestionListShortAnswer",resourceQuestionListShortAnswer);
//		AlisaYe20170703---新的页面修改部分控制器（题型分成四类分别处理）


			Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
			ca.setTime(endDate); //设置时间为当前时间
			int year = ca.get(Calendar.YEAR);//获取年份
			int month=ca.get(Calendar.MONTH)+1;//获取月份
			int day=ca.get(Calendar.DATE);//获取日
			int hour=ca.get(Calendar.HOUR_OF_DAY);//小时
			int minute=ca.get(Calendar.MINUTE);//分
			int second=ca.get(Calendar.SECOND);//秒    2017/05/16 20:27:30
			//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
			String teachExamEndDate=year+"/"+month+"/"+day+" "+hour+":"+minute+":"+second;

			model.addAttribute("teachExamEndDate",teachExamEndDate);
			//*********************stuExamDoTest的控制器方法************************
			return "modules/teach/stuExamDoTest";
		}else{
//			Page<TeachExam> page = teachExamService.findExamListPageById(new Page<TeachExam>(request, response), teachExam,userId);
			teachExam.setUserId(UserUtils.getUser().getId());
			Page<TeachExam> page = teachExamService.findExamListPageById(new Page<TeachExam>(request, response), teachExam);
			model.addAttribute("page", page);
			return "modules/teach/stuExamList";
		}

	}




}